#!/bin/sh
# shellcheck shell=dash disable=SC2169,SC3010
#
# Starts eq3configd.
#

DAEMON="eq3configd"
PIDFILE="/var/run/${DAEMON}.pid"

init () {

	# we output the BidCos-Address and the
	# SerialNumber to /var/ids
	echo "BidCoS-Address=$(cat /var/rf_address)" >/var/ids
	echo "SerialNumber=$(cat /var/board_serial)" >>/var/ids

	# in case we have a BidCos-RF device (no empty /var/rf_address)
	# and there is no already existing /etc/config/ids we have to
	# copy it over
	if [[ -s /var/rf_address ]] && [[ ! -e /etc/config/ids ]] ; then
		cp /var/ids /etc/config/
	fi

	# make sure crypttool.cfg exists and has secure permissions
	if [[ ! -e /etc/config/crypttool.cfg ]] ; then
		touch /etc/config/crypttool.cfg
	fi
	chmod 0640 /etc/config/crypttool.cfg
	chgrp eq3cfg /etc/config/crypttool.cfg
}

start() {
	echo -n "Starting ${DAEMON}: "
	init

	# adjust the oom score (which is inherited by start-stop-daemon)
	# to ensure that others are killed first in case of low memory situations
	echo -900 >/proc/$$/oom_score_adj 2> /dev/null

	start-stop-daemon -S -q -b -m -c eq3cfg:eq3cfg -p ${PIDFILE} --exec /bin/${DAEMON}
	echo "OK"
}
stop() {
	echo -n "Stopping ${DAEMON}: "
	start-stop-daemon -K -q -p ${PIDFILE}
	rm -f ${PIDFILE}
	echo "OK"
}
restart() {
	stop
	start
}

case "$1" in
	start)
		start
	;;
	stop)
		stop
	;;
	restart|reload)
		restart
	;;
	*)
	echo "Usage: $0 {start|stop|restart}"
	exit 1
esac

exit 0
